﻿Namespace SchoolClick.Database.DAL

    Public Interface IUsuarios_Roles
        ReadOnly Property IUsuariosYRoles As IUsuarios_Roles

        Function ValidarUsuario(Usuario As String, Password As String) As Boolean
        Function RolExist(NombreRol As String) As Boolean
        Function GetRoles_For_User(Username As String) As String
        Function IsUser_in_Rol(Usuario As String, Rol As String) As Boolean
        Function GetTopMenu(RoleName As String) As IEnumerable(Of MENUBAR)
        Function GetSubMenu(RoleName As String, Parent As String) As IEnumerable(Of MENUBAR)
        Function IsExist(usuario As String) As Boolean
        Sub ChangePassword(IDUsuario As String, OldPassword As String, NewPassword As String)
    End Interface

    Partial Public Class SchoolClickDAL
        Implements IUsuarios_Roles

        Public ReadOnly Property IUsuariosYRoles As IUsuarios_Roles Implements IUsuarios_Roles.IUsuariosYRoles
            Get
                Return DirectCast(Me, IUsuarios_Roles)
            End Get
        End Property

        ''' <summary>
        ''' Comprueba en la base de datos si las credenciales son validas en el sistema
        ''' </summary>
        ''' <param name="Usuario">Nombre del usuario que se desea comprobar</param>
        ''' <param name="Password">Contraseña del usuario que se desea comprobar</param>
        ''' <returns>Retorna 'Verdadero', si el usuario es valido en el sistema, de lo contrario 'Falso'</returns>
        ''' <remarks></remarks>
        Private Function ValidarUsuario(Usuario As String, Password As String) As Boolean Implements IUsuarios_Roles.ValidarUsuario
            Dim iResult As Integer = 0
            Try
                Using cnn As New SchoolClickEntities
                    iResult = cnn.VALIDATION_USER(Usuario, Password).SingleOrDefault()
                End Using
            Catch ex As Exception
                Throw ex
            End Try
            Return If(iResult = 0, False, True)
        End Function

        ''' <summary>
        ''' Devuelve los roles especificados en el sistema del usuario indicado
        ''' </summary>
        ''' <param name="Username">Nombre del usuario del cual se desea obtener el rol dentro de la APP</param>
        ''' <returns>Retorna el rol al que pertenece el usuario en una cadena de texto</returns>
        ''' <remarks></remarks>
        Private Function GetRoles_For_User(Username As String) As String Implements IUsuarios_Roles.GetRoles_For_User
            Dim sRol = String.Empty

            Try
                Using cnn As New SchoolClickEntities
                    sRol = cnn.GETROLES_FOR_USER(Username).SingleOrDefault()
                End Using
            Catch ex As Exception
                Throw ex
            End Try
            Return sRol
        End Function

        ''' <summary>
        ''' Verifica si el usuario especificado pertenece al rol especificado
        ''' </summary>
        ''' <param name="Usuario">Nombre del usuario del cual se desea verificar el rol</param>
        ''' <param name="Rol">Nombre del rol el cual se verificar si pertenece al usuario especificado</param>
        ''' <returns></returns>
        ''' <remarks></remarks>
        Private Function IsUser_in_Rol(Usuario As String, Rol As String) As Boolean Implements IUsuarios_Roles.IsUser_in_Rol
            Dim iResult = 0
            Try
                Using cnn As New SchoolClickEntities
                    iResult = cnn.ISUSER_IN_ROLE(Usuario, Rol).SingleOrDefault
                End Using
            Catch ex As Exception
                Throw ex
            End Try

            Return If(iResult = 0, False, True)
        End Function

        ''' <summary>
        ''' Verifica si el Rol que se pasa, es un Rol valido
        ''' </summary>
        ''' <param name="NombreRol">Nombre del Rol que se desea comprobar</param>
        ''' <returns>Retorna 'VERDADERO' si el Nombre de Rol es valido en la base de datos, de lo contrario 'FALSO'</returns>
        ''' <remarks></remarks>
        Private Function RolExist(NombreRol As String) As Boolean Implements IUsuarios_Roles.RolExist
            Dim iResult = 0
            Try
                Using cnn As New SchoolClickEntities
                    iResult = cnn.ROLEEXIST(NombreRol).SingleOrDefault()
                End Using
            Catch ex As Exception
                Throw ex
            End Try
            Return If(iResult = 0, False, True)
        End Function

        Private Function GetTopMenu(RoleName As String) As IEnumerable(Of MENUBAR) Implements IUsuarios_Roles.GetTopMenu
            Try
                Using cnn As New SchoolClickEntities
                    Return cnn.GET_MENUBAR_BY_ROL(RoleName).Where(Function(m) m.ID_PARENT = 0).ToArray
                End Using
            Catch ex As Exception
                Return New MENUBAR() {}
            End Try
        End Function

        Private Function GetSubMenu(RoleName As String, Parent As String) As IEnumerable(Of MENUBAR) Implements IUsuarios_Roles.GetSubMenu
            Try
                Dim arrSubMenus As List(Of MENUBAR)
                Using cnn As New SchoolClickEntities
                    arrSubMenus = cnn.GET_SUBMENUBAR_BY_ROL(RoleName, Parent).ToList

                    'Ahora comprobamos si se encontro un elemento, sino se encuentra vamos a crear uno por defecto con el mismo nombre del padre
                    If arrSubMenus.Count.Equals(0) Then
                        Dim menuParent = cnn.GET_MENUBAR_BY_ROL(RoleName).Where(Function(m) m.NOMBRE_MENU = Parent).SingleOrDefault
                        arrSubMenus.Add(menuParent)
                    End If
                End Using
                Return arrSubMenus
            Catch ex As Exception
                Return New MENUBAR() {}
            End Try
        End Function

        Private Function IsExist(usuario As String) As Boolean Implements IUsuarios_Roles.IsExist
            Dim cnn As New SchoolClickEntities
            Try
                Dim r = cnn.USUARIOS.Where(Function(u) u.ID_USUARIO = usuario).SingleOrDefault
                Return If(r IsNot Nothing, True, False)
            Catch ex As Exception
                ex.Data.Clear()
                Return True
            Finally
                cnn.Dispose()
            End Try
        End Function

        Private Sub ChangePassword(IDUsuario As String, OldPassword As String, NewPassword As String) Implements IUsuarios_Roles.ChangePassword
            Dim cnn As New SchoolClickEntities
            Try
                cnn.OP_CHANGE_PASSWORD(IDUsuario, OldPassword, NewPassword,
                                       ConfigurationManager.AppSettings("Rol_ERA").ToSecureString.ToStringInseguro)
            Catch ex As EntityCommandExecutionException
                Throw New EntityCommandExecutionException(ex.InnerException.Message, ex)
            Catch ex As Exception
                Throw ex
            Finally
                cnn.Dispose()
            End Try
        End Sub
    End Class
End Namespace
